/**
 * 项目状态流转组件
 * 用于展示和处理项目状态流转操作
 */

// 使用统一配置入口导入所需模块
const { projectStateService } = require('../../config/services_config');
const { statusHelper } = require('../../config/project_helpers_config');

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 当前项目数据
    project: {
      type: Object,
      value: null,
      observer: 'onProjectChanged'
    },
    
    // 当前用户角色
    role: {
      type: String,
      value: 'visitor'
    }
  },
  
  /**
   * 组件的初始数据
   */
  data: {
    // 可用状态事件
    availableEvents: [],
    
    // 事件模态框数据
    showEventModal: false,
    currentEvent: null,
    eventComment: '',
    formData: {},
    
    // 历史记录数据
    historyList: [],
    historyPage: 1,
    historySize: 10,
    historyTotal: 0,
    historyHasMore: false,
    
    // 状态图谱数据
    graphData: null,
    
    // 加载状态
    loading: {
      events: false,
      history: false,
      transition: false
    },
    
    // 错误信息
    error: null
  },
  
  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached() {
      this.loadStateData();
    },
    
    detached() {
      // 清理工作
    }
  },
  
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 当项目数据变更时触发
     */
    onProjectChanged(newVal) {
      if (newVal) {
        this.loadStateData();
      }
    },
    
    /**
     * 加载状态相关数据
     */
    async loadStateData() {
      const project = this.data.project;
      if (!project || !project._id) return;
      
      this.setData({
        error: null
      });
      
      // 计算状态名称
      this._calculateStatusNames(project);
      
      // 加载可用事件
      await this.loadAvailableEvents();
      
      // 加载状态历史
      await this.loadStateHistory();
    },
    
    /**
     * 计算状态名称信息
     * @param {Object} project 项目数据
     * @private
     */
    _calculateStatusNames(project) {
      if (!project) return;
      
      try {
        const ResearchProjectModel = require('../../model/research_project_model');
        
        // 获取状态名称
        const level1Name = ResearchProjectModel.LEVEL_1_NAMES[project.level1] || '未知状态';
        const level2Name = project.level2 ? (ResearchProjectModel.LEVEL_2_NAMES[project.level2] || project.level2) : '';
        const level3Name = project.level3 ? (ResearchProjectModel.LEVEL_3_NAMES[project.level3] || project.level3) : '';
        const level4Name = project.level4 || '';
        
        // 更新项目数据中的状态名称
        const updatedProject = {
          ...project,
          level1Name,
          level2Name,
          level3Name,
          level4Name
        };
        
        this.setData({
          project: updatedProject
        });
        
      } catch (error) {
        console.error('[项目状态流转组件] 计算状态名称出错:', error);
      }
    },
    
    /**
     * 加载可用状态事件
     */
    async loadAvailableEvents() {
      const project = this.data.project;
      const role = this.data.role;
      
      if (!project || !project._id) return;
      
      this.setData({
        'loading.events': true,
        error: null
      });
      
      try {
        const events = await projectStateService.getAvailableEvents(project, role);
        
        this.setData({
          availableEvents: events,
          'loading.events': false
        });
        
      } catch (error) {
        console.error('[项目状态流转组件] 加载可用事件出错:', error);
        this.setData({
          'loading.events': false,
          error: '加载可用事件失败: ' + error.message
        });
      }
    },
    
    /**
     * 加载状态历史记录
     */
    async loadStateHistory(page = 1) {
      const project = this.data.project;
      if (!project || !project._id) return;
      
      this.setData({
        'loading.history': true,
        error: null
      });
      
      try {
        const options = {
          page: page,
          size: this.data.historySize,
          branchId: project.branchId || ''
        };
        
        const result = await projectStateService.getStateHistory(project._id, options);
        
        // 格式化历史记录
        if (result.list && Array.isArray(result.list)) {
          result.list.forEach(item => {
            item.fromStateText = statusHelper.getFullStatusDesc(item.fromState);
            item.toStateText = statusHelper.getFullStatusDesc(item.toState);
          });
        }
        
        this.setData({
          historyList: page === 1 ? result.list : [...this.data.historyList, ...result.list],
          historyTotal: result.total,
          historyPage: page,
          historyHasMore: result.list.length + (page - 1) * this.data.historySize < result.total,
          'loading.history': false
        });
        
      } catch (error) {
        console.error('[项目状态流转组件] 加载状态历史记录出错:', error);
        this.setData({
          'loading.history': false,
          error: '加载状态历史记录失败: ' + error.message
        });
      }
    },
    
    /**
     * 加载更多历史记录
     */
    loadMoreHistory() {
      if (this.data.historyHasMore && !this.data.loading.history) {
        this.loadStateHistory(this.data.historyPage + 1);
      }
    },
    
    /**
     * 创建状态图谱
     */
    async createStateGraph() {
      const project = this.data.project;
      if (!project || !project._id) return;
      
      this.setData({
        'loading.graph': true,
        error: null
      });
      
      try {
        const graphData = await projectStateService.createStateGraph(project._id);
        
        this.setData({
          graphData,
          'loading.graph': false
        });
        
        // 触发图谱创建完成事件
        this.triggerEvent('graphCreated', { graphData });
        
      } catch (error) {
        console.error('[项目状态流转组件] 创建状态图谱出错:', error);
        this.setData({
          'loading.graph': false,
          error: '创建状态图谱失败: ' + error.message
        });
      }
    },
    
    /**
     * 打开事件模态框
     */
    openEventModal(e) {
      const eventId = e.currentTarget.dataset.eventId;
      const event = this.data.availableEvents.find(evt => evt.id === eventId);
      
      if (!event) return;
      
      this.setData({
        showEventModal: true,
        currentEvent: event,
        eventComment: '',
        formData: {}
      });
    },
    
    /**
     * 关闭事件模态框
     */
    closeEventModal() {
      this.setData({
        showEventModal: false,
        currentEvent: null,
        eventComment: '',
        formData: {}
      });
    },
    
    /**
     * 提交状态流转
     */
    async submitStateTransition() {
      const project = this.data.project;
      const event = this.data.currentEvent;
      const comment = this.data.eventComment;
      
      if (!project || !event) return;
      
      // 构造当前状态对象
      const currentStatus = {
        level1: project.level1,
        level2: project.level2,
        level3: project.level3 || '',
        level4: project.level4 || ''
      };
      
      // 构造目标状态对象
      const targetStatus = {
        level1: event.toState.level1,
        level2: event.toState.level2,
        level3: event.toState.level3 || '',
        level4: event.toState.level4 || ''
      };
      
      this.setData({
        'loading.transition': true,
        error: null
      });
      
      try {
        // 执行状态转换
        const result = await projectStateService.executeStateTransition(
          project._id,
          currentStatus,
          targetStatus,
          {
            reason: comment,
            eventType: event.id,
            formData: this.data.formData
          }
        );
        
        // 关闭模态框
        this.closeEventModal();
        
        // 通知父组件状态已更新
        this.triggerEvent('stateUpdated', { 
          project: result.data,
          prevState: currentStatus,
          newState: targetStatus,
          event: event
        });
        
        // 更新本地数据
        this.loadStateData();
        
        // 状态转换成功提示
        wx.showToast({
          title: '状态更新成功',
          icon: 'success'
        });
        
      } catch (error) {
        console.error('[项目状态流转组件] 状态转换出错:', error);
        this.setData({
          'loading.transition': false,
          error: '状态转换失败: ' + error.message
        });
        
        wx.showModal({
          title: '状态转换失败',
          content: error.message || '未知错误',
          showCancel: false
        });
      }
    },
    
    /**
     * 表单数据变更处理
     */
    onFormDataChange(e) {
      const field = e.currentTarget.dataset.field;
      const value = e.detail.value;
      
      this.setData({
        [`formData.${field}`]: value
      });
    },
    
    /**
     * 评论内容变更处理
     */
    onCommentChange(e) {
      this.setData({
        eventComment: e.detail.value
      });
    },
    
    /**
     * 验证状态转换
     */
    async validateTransition(currentStatus, targetStatus) {
      try {
        return await projectStateService.validateStateTransition(currentStatus, targetStatus);
      } catch (error) {
        console.error('[项目状态流转组件] 验证状态转换出错:', error);
        return {
          valid: false,
          reason: '验证状态转换时出错: ' + error.message
        };
      }
    }
  }
}) 